package com.yzy.utils;

//import org.apache.commons.codec.binary.Hex;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;

/**
 * Description:
 * Date: 2020-03-20
 *
 * @author youzhiyong
 */
public class TestUploadImg {

    private static String privateKey = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDXxXmipDlUKE7O3r/VR5qT6duChq5dbFXbdVj46FZRlEFVLULe1044r+R3ucQrpo76mUDMhLKkfwRoUWY+1bkhPwRn7AME6+h7IzbEDbeeaRN0qNgjIW6h6+dHxaiyMOA3vxpqWqyT9Htyhs9iIZKcCswF/FDVMSnldUw32YKwuJHOeo4G97V26OTMH0xBFzjnwkd0E1CsmFNl3lkHtjvdnCkEQ8R2kwyizVrH5Vrq8lFzRpLAKo5QE6EWd0qXkcso08n8dejzFIPJBndVs2QVTfmU5vAP3PQ4zqUSOYHmKupBMJXaQ2y17erUBFvBvJqIs8Udk1RPyRWumFL9Jr6rAgMBAAECggEBAICJejFiRWiV7oSb+4lRc4tD1+lE1CCBRhBLMqpstec5O0ZDhT984XMxjRepiWw7d5dfrlNnhYgqxnRicVdjODrO8I/777yB0GdyjdBzH3x1ugpX/xHGe8Jn5spBvIISTa/H3zOWOpKVJOkP2ADsYQsl/25dZcXq2LuBidsHbyxYXvBvhB2dk9PaRnPHxZvdRJQh5BoGSZtduyKkDRufRLM7MvdkvlnhiaFVcryXdaOnqiyoHEIa8bmFsqkxeodPWsJMV3hdRf1jhHNeHz2QLgroCFXkNT3S1Pp8lVaCT3KeHU+3LMgnU68NDtnrSl92xTTpo45XVy5YAcrqpqc7fCkCgYEA9au0fJRGe878pPAolwVfPGua4s6+aeSkms5LH5U6xm0aMyQ1nnKonuViMLXjJrHquNN9tNNatPRhOB04pPF8fsq0MP2qDT/PVoJncY9WV1U6u43/F52dYu+4q0z6fF2vaCSfQ3bkenCJ8PUTWljkjmoI1vqIwj+4vJI2VtKrjecCgYEA4NfyR6EejPgSKUadgElERlzH9uyyoEe8mQ5YN7zndDC58dGoVG+ted8g8wq/nTCYWQK0b2iO6FaebdVNwbcKeM7jGIWWhq6E/HHw30k+G+I+ibejd069lCYefqAgzLp/RcX09JJwFNhBCIhuZahjj4jvUZ98FDgHYH6qdUdCiJ0CgYBfJIl4ud/2MPptUkkV+9GfT7kjX5gk4JTTE1PKvnuNv1EnPz24yIT/TKzTWo3HPZ4+yEFl13jIneBM4BxA3PkvDYftdT/3c5/zy/sN4so4dlyRqHODjNoYJ+joBp73rTyyY4R+lzvzI0R42iENm2GgufYEc/Ck8hK0jReYVmx0PwKBgERUvHfSWmODHJnYsRMEsTAlEExVoO+e/Y0SU/MUgM7J5Ci+i8albfYkvnG+aX9O/m3GqalWAGBRurIsagYeJ5uRXGjeaGGj9hx2UDq7mpmEx3a5DX+7uVelwgy/g1hUsUs2HvyY6GEdW55JQCu64g8EEZ8ftei7IlrMA+fCcVDtAoGAenRsF2E0bfoSEjbBBYYiBf0cgB+ixATomecxDGOKA2DbpW84YLfIsJscUb0SkWd+De+I7Kc5JMEtQ0DBSfVKbhnYcvAgEH+VuyIv9cAlZqIdt0+9+fv/RefYkSiKJ44T58rgT2jEMQKjAjWKmr9hvk6vcXfG4FsxMpJdm4sRy0o=";
    private static String merchantId = "1237402102";
    private static String serialNo = "77BAFDE0E1FC091B78E27BF3DF50E2DD8FA00877";


    public static void main(String[] args) {
        String fileName = "logo.png";
        String filePath = "C:\\Users\\Administrator\\Desktop\\blog.bak\\logo.png";
        String urlStr = "https://api.mch.weixin.qq.com/v3/marketing/favor/media/image-upload";
        String meta = "{\"filename\":\"" + fileName + "\",\"sha256\":\"1360b8de821e640a24ffa81ce94ec62ead99b1cfb969dae02f96e1ffafbabe8f\"}";
        String auth = SignUtils.getAuth("POST", "/v3/marketing/favor/media/image-upload", meta);
        DataOutputStream out = null;
        BufferedReader in = null;
        String res = "";
        try {
            URL url = new URL(urlStr);

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setDoInput(true);

            String boundary = "---youzhiyong";
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");
            conn.addRequestProperty("Authorization", auth);
            conn.addRequestProperty("Accept", "application/json");
            conn.setRequestProperty("User-Agent", "PostmanRuntime/7.6.0");
            conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
            conn.connect();

            out = new DataOutputStream(conn.getOutputStream());
            StringBuilder sb1 = new StringBuilder();
            sb1.append("--" + boundary + "\r\n")
                    .append("Content-Disposition: form-data; name=\"meta\"\r\n")
                    .append("Content-Type: application/json\r\n")
                    .append("\r\n")
                    .append(meta + "\r\n")
                    .append("--" + boundary + "\r\n")
                    .append("Content-Disposition: form-data; name=\"file\"; filename=\"" + fileName + "\"\r\n")
                    .append("Content-Type: image/png\r\n")
                    .append("\r\n");
            out.write(sb1.toString().getBytes());


            DataInputStream in2 = new DataInputStream(new FileInputStream(new File(filePath)));
            int bts = 0;
            byte[] buffer = new byte[1024];
            while ((bts=in2.read(buffer)) != -1) {
                out.write(buffer, 0, bts);
            }
            in2.close();

            out.write("\r\n".getBytes());
            StringBuilder sb3 = new StringBuilder();
            sb3.append("--" + boundary + "--\r\n");

            out.write(sb3.toString().getBytes());

            out.flush();
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));

            String line;
            while ((line = in.readLine()) != null) {
                res += line;
            }
            System.out.println(res);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 生成签名
     */
    static class SignUtils {

        public static String getAuth(String method, String url, String body) {
            long time = System.currentTimeMillis();
            String nonceStr = time + "";
            long timestamp = time / 1000;
            String message = buildMessage(method, url, timestamp, nonceStr, body);
            String signature = sign(message, privateKey);

            return "WECHATPAY2-SHA256-RSA2048 mchid=\"" + merchantId + "\","   //商户id
                    + "nonce_str=\"" + nonceStr + "\","                                //随机字符串
                    + "timestamp=\"" + timestamp + "\","                               //时间戳
                    + "serial_no=\"" + serialNo + "\","                                //证书序列号
                    + "signature=\"" + signature + "\"";                               //签名
        }

        private static String sign(String message, String privateKey) {
            try {
                Signature sign = Signature.getInstance("SHA256withRSA");
                sign.initSign(getPrivateKey(privateKey));
                sign.update(message.getBytes("utf-8"));
                return Base64.getEncoder().encodeToString(sign.sign());
            } catch (InvalidKeyException | NoSuchAlgorithmException | InvalidKeySpecException | SignatureException | UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            return null;

        }

        private static PrivateKey getPrivateKey(String privateKey) throws NoSuchAlgorithmException, InvalidKeySpecException {
            byte[] bytes = Base64.getDecoder().decode(privateKey);
            KeySpec keySpec = new PKCS8EncodedKeySpec(bytes);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            return keyFactory.generatePrivate(keySpec);
        }

        private static String buildMessage(String method, String url, long timestamp, String nonceStr, String body) {
            /*String canonicalUrl = url.encodedPath();
            if (url.encodedQuery() != null) {
                canonicalUrl += "?" + url.encodedQuery();
            }*/

            return method + "\n"
                    + url + "\n"
                    + timestamp + "\n"
                    + nonceStr + "\n"
                    + body + "\n";
        }
    }

    /**
     * 生成文件摘要
     * @param str
     * @return
     */
 /*   public static String getSHA256Str(String str){
        MessageDigest messageDigest;
        String encdeStr = "";
        try {
            messageDigest = MessageDigest.getInstance("SHA-256");
            byte[] hash = messageDigest.digest(str.getBytes("UTF-8"));
            System.out.println(Base64.getEncoder().encodeToString(hash));
            System.out.println(Hex.encodeHexString(hash));
            encdeStr = Hex.encodeHexString(hash);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return encdeStr;
    }
*/
}
